package com.cavas.domain.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cavas.domain.bean.Membre;
import com.cavas.domain.dao.DaoMembre;
@Service("userDetailsService")
@Transactional(readOnly =true)
public class CustomUserDetailsService implements UserDetailsService {

	 @Autowired
	 private DaoMembre daoMembre;
	 
	@Override
	public UserDetails loadUserByUsername(String eemail)
			throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		Membre membre = daoMembre.findByMail(eemail);
        boolean enabled = true;  
        boolean accountNonExpired = true;  
        boolean credentialsNonExpired = true;  
        boolean accountNonLocked = true;  
  
        return new User(  
                membre.getEmail(),   
                membre.getPassword(),   
                enabled,   
                accountNonExpired,   
                credentialsNonExpired,   
                accountNonLocked,  
                getAuthorities(membre.getFonction().getId())  
        );
	}
	
	public Collection<? extends GrantedAuthority> getAuthorities(Integer fonction){
		List<GrantedAuthority> authList = getGrantedAuthorities(getFonction(fonction));
		return authList;
		
	}

	private List<String> getFonction(Integer fonction) {
		List<String> fonctions = new ArrayList<String>();
		if (fonction.intValue() == 1){
			fonctions.add("ROLE_USER");
			fonctions.add("ROLE_MODERATEUR");
			fonctions.add("ROLE_ADMIN");
		}
		else if(fonction.intValue() == 2){
			fonctions.add("ROLE_USER");	
		    fonctions.add("ROLE_MODERATEUR");
		}
		else if(fonction.intValue() == 3){
			fonctions.add("ROLE_USER");	
		}
		return fonctions;
	}
	
	public static List<GrantedAuthority> getGrantedAuthorities(List<String> fonctions){
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for(String fonction : fonctions)
				authorities.add(new SimpleGrantedAuthority(fonction));
		
		return authorities;
	}

}
